import asyncio
import aiomysql
import uuid
import random
import hashlib
import argparse
from datetime import datetime, timedelta
import sys
import os

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

# 导入项目相关模块
from backend.models.user import User, Role, Permission, Department
from backend.services.user_service import UserService, RoleService, PermissionService, DepartmentService
from tortoise import Tortoise
from backend.common.database import TORTOISE_ORM


DB_CONFIG = {
    "host": "127.0.0.1",
    "user": "root",
    "password": "123456",
    "db": "fd_plateform",
    "port": 3306,
    "charset": "utf8mb4",
    "autocommit": True,
}




# 预定义权限数据
DEFAULT_PERMISSIONS = [
    # 用户相关权限
    {"name": "用户查询", "code": "user:list", "description": "查看用户列表"},
    {"name": "用户创建", "code": "user:create", "description": "创建用户"},
    {"name": "用户更新", "code": "user:update", "description": "更新用户信息"},
    {"name": "用户删除", "code": "user:delete", "description": "删除用户"},
    
    # 角色相关权限
    {"name": "角色查询", "code": "role:list", "description": "查看角色列表"},
    {"name": "角色创建", "code": "role:create", "description": "创建角色"},
    {"name": "角色更新", "code": "role:update", "description": "更新角色信息"},
    {"name": "角色删除", "code": "role:delete", "description": "删除角色"},
    
    # 部门相关权限
    {"name": "部门查询", "code": "department:list", "description": "查看部门列表"},
    {"name": "部门创建", "code": "department:create", "description": "创建部门"},
    {"name": "部门更新", "code": "department:update", "description": "更新部门信息"},
    {"name": "部门删除", "code": "department:delete", "description": "删除部门"},
    
    # 权限相关权限
    {"name": "权限查询", "code": "permission:list", "description": "查看权限列表"},
    {"name": "权限创建", "code": "permission:create", "description": "创建权限"},
    {"name": "权限更新", "code": "permission:update", "description": "更新权限信息"},
    {"name": "权限删除", "code": "permission:delete", "description": "删除权限"},

    # 智能体相关权限
    {"name": "智能体查询", "code": "agent:list", "description": "查看智能体列表"},
    {"name": "智能体创建", "code": "agent:create", "description": "创建智能体"},
    {"name": "智能体更新", "code": "agent:update", "description": "更新智能体信息"},
    {"name": "智能体删除", "code": "agent:delete", "description": "删除智能体"},
    
    # 日志相关权限
    {"name": "请求日志查询", "code": "log:request", "description": "查看请求日志"},
    {"name": "登录历史查询", "code": "log:login", "description": "查看登录历史"},
    
    # 任务相关权限
    {"name": "任务查询", "code": "task:list", "description": "查看任务列表"},
    {"name": "任务创建", "code": "task:create", "description": "创建任务"},
    {"name": "任务更新", "code": "task:update", "description": "更新任务信息"},
    {"name": "任务删除", "code": "task:delete", "description": "删除任务"},
]



# 预定义角色数据
DEFAULT_ROLES = [
    {
        "name": "超级管理员",
        "code": "admin",
        "description": "系统超级管理员，拥有所有权限",
        "permissions": ["*"],  # 所有权限
        "dept_id": "0001A110000000000DHB"  # 总公司
    }
]

# 扩展角色定义，用于测试
EXTENDED_ROLES = [
    {
        "name": "用户管理员",
        "code": "user_admin",
        "description": "负责用户管理的管理员角色",
        "permissions": ["user:list", "user:create", "user:update", "user:delete"],
        "dept_id": "tech"  # 技术部
    },
    {
        "name": "RPA操作员",
        "code": "rpa_operator",
        "description": "RPA操作员，可以操作任务相关功能",
        "permissions": ["task:list", "task:create", "task:update"],
        "dept_id": "finance"  # 财务部
    },
    {
        "name": "审计员",
        "code": "auditor",
        "description": "系统审计员，可以查看各种日志",
        "permissions": ["log:request", "log:login"],
        "dept_id": "hr"  # 人事部
    },
    {
        "name": "普通用户",
        "code": "user",
        "description": "普通用户，只有基本查询权限",
        "permissions": ["user:list", "role:list", "department:list", "task:list"],
        "dept_id": "rd"  # 研发部
    }
]

# 预定义部门数据
DEFAULT_DEPARTMENTS = [
    {
        "dept_id": "0001A110000000000DHB",
        "dept_name": "总公司",
        "description": "公司总部",
        "parent_id": None,
        "level": 1,
        "order_num": 1
    },
    {
        "dept_id": "tech",
        "dept_name": "技术部",
        "description": "负责技术研发",
        "parent_id": "0001A110000000000DHB",
        "level": 2,
        "order_num": 1
    },
    {
        "dept_id": "rd",
        "dept_name": "研发部",
        "description": "负责产品研发",
        "parent_id": "tech",
        "level": 3,
        "order_num": 1
    },
    {
        "dept_id": "qa",
        "dept_name": "测试部",
        "description": "负责产品测试",
        "parent_id": "tech",
        "level": 3,
        "order_num": 2
    },
    {
        "dept_id": "finance",
        "dept_name": "财务部",
        "description": "负责公司财务",
        "parent_id": "0001A110000000000DHB",
        "level": 2,
        "order_num": 2
    },
    {
        "dept_id": "hr",
        "dept_name": "人事部",
        "description": "负责人事管理",
        "parent_id": "0001A110000000000DHB",
        "level": 2,
        "order_num": 3
    }
]

# 模拟用户头像路径列表
AVATARS = [
    "avatars/23e5f46b-03d2-4d18-aac0-9b689b58fb84.png",
    "avatars/341a76c2-2bbe-4d53-984b-80f95ab586f3.png",
    "avatars/9c0a2f50-6d63-40d8-9870-734f01125e81.png",
    "avatars/a04d16e3-5c88-4a7a-8c98-8d74e171b19c.png",
    "avatars/b3bf836c-52e0-4243-8140-ed37d7e76405.png"
]


def get_md5_hash(value):
    return hashlib.md5(value.encode('utf-8')).hexdigest()



async def init_tortoise():
    """初始化 Tortoise ORM"""
    await Tortoise.init(config=TORTOISE_ORM)


async def close_tortoise():
    """关闭 Tortoise ORM 连接"""
    await Tortoise.close_connections()


async def init_permissions():
    """初始化权限"""
    print("=== 开始初始化权限 ===")
    for perm_data in DEFAULT_PERMISSIONS:
        # 检查权限是否已存在
        existing_perm = await Permission.filter(code=perm_data["code"]).first()
        if not existing_perm:
            await PermissionService.create_permission(
                name=perm_data["name"],
                code=perm_data["code"],
                description=perm_data["description"]
            )
            print(f"✅ 创建权限: {perm_data['name']} ({perm_data['code']})")
        else:
            print(f"⏩ 权限已存在: {perm_data['name']} ({perm_data['code']})")
    
    print("✅ 权限初始化完成")


async def init_departments():
    """初始化部门"""
    print("=== 开始初始化部门 ===")
    
    # 先创建顶层部门
    for dept_data in [d for d in DEFAULT_DEPARTMENTS if d["parent_id"] is None]:
        existing_dept = await Department.filter(dept_id=dept_data["dept_id"]).first()
        if not existing_dept:
            dept = await Department.create(
                dept_id=dept_data["dept_id"],
                dept_name=dept_data["dept_name"],
                description=dept_data["description"],
                parent_id=None,
                level=dept_data["level"],
                order_num=dept_data["order_num"]
            )
            print(f"✅ 创建部门: {dept.dept_name}")
        else:
            print(f"⏩ 部门已存在: {existing_dept.dept_name}")
    
    # 创建二级部门
    for dept_data in [d for d in DEFAULT_DEPARTMENTS if d["parent_id"] is not None and d["level"] == 2]:
        existing_dept = await Department.filter(dept_id=dept_data["dept_id"]).first()
        if not existing_dept:
            parent_dept = await Department.filter(dept_id=dept_data["parent_id"]).first()
            if parent_dept:
                dept = await Department.create(
                    dept_id=dept_data["dept_id"],
                    dept_name=dept_data["dept_name"],
                    description=dept_data["description"],
                    parent_id=parent_dept.dept_id,
                    ancestors=parent_dept.dept_id,
                    level=dept_data["level"],
                    order_num=dept_data["order_num"]
                )
                print(f"✅ 创建部门: {dept.dept_name} (父部门: {parent_dept.dept_name})")
            else:
                print(f"⚠️ 无法创建部门 {dept_data['dept_name']}: 找不到父部门 {dept_data['parent_id']}")
        else:
            print(f"⏩ 部门已存在: {existing_dept.dept_name}")
    
    # 创建三级及以下部门
    for dept_data in [d for d in DEFAULT_DEPARTMENTS if d["parent_id"] is not None and d["level"] > 2]:
        existing_dept = await Department.filter(dept_id=dept_data["dept_id"]).first()
        if not existing_dept:
            parent_dept = await Department.filter(dept_id=dept_data["parent_id"]).first()
            if parent_dept:
                ancestors = f"{parent_dept.ancestors or parent_dept.dept_id}/{parent_dept.dept_id}" if parent_dept.ancestors else parent_dept.dept_id
                dept = await Department.create(
                    dept_id=dept_data["dept_id"],
                    dept_name=dept_data["dept_name"],
                    description=dept_data["description"],
                    parent_id=parent_dept.dept_id,
                    ancestors=ancestors,
                    level=dept_data["level"],
                    order_num=dept_data["order_num"]
                )
                print(f"✅ 创建部门: {dept.dept_name} (父部门: {parent_dept.dept_name})")
            else:
                print(f"⚠️ 无法创建部门 {dept_data['dept_name']}: 找不到父部门 {dept_data['parent_id']}")
        else:
            print(f"⏩ 部门已存在: {existing_dept.dept_name}")
    
    # 初始化部门权限
    await init_department_permissions()
    
    print("✅ 部门初始化完成")


async def init_department_permissions():
    """初始化部门权限"""
    print("=== 开始初始化部门权限 ===")
    all_permissions = await Permission.all()
    perm_dict = {p.code: p for p in all_permissions}
    
    # 技术部门权限
    tech_dept = await Department.filter(dept_id="tech").first()
    if tech_dept:
        # 技术部可以查看所有日志
        log_permissions = [perm for code, perm in perm_dict.items() if code.startswith("log:")]
        if log_permissions:
            await tech_dept.permissions.add(*log_permissions)
            print(f"✅ 为技术部门添加了 {len(log_permissions)} 个日志相关权限")
            
    # 财务部门权限
    finance_dept = await Department.filter(dept_id="finance").first()
    if finance_dept:
        # 财务部可以查看财务相关功能
        finance_permissions = [
            perm_dict.get("report:list"), 
            perm_dict.get("report:export"),
            perm_dict.get("dashboard:view")
        ]
        finance_permissions = [p for p in finance_permissions if p]
        if finance_permissions:
            await finance_dept.permissions.add(*finance_permissions)
            print(f"✅ 为财务部门添加了 {len(finance_permissions)} 个财务相关权限")
            
    # 人事部门权限
    hr_dept = await Department.filter(dept_id="hr").first()
    if hr_dept:
        # 人事部可以查看用户信息
        hr_permissions = [
            perm_dict.get("user:list"), 
            perm_dict.get("user:view"),
            perm_dict.get("department:list")
        ]
        hr_permissions = [p for p in hr_permissions if p]
        if hr_permissions:
            await hr_dept.permissions.add(*hr_permissions)
            print(f"✅ 为人事部门添加了 {len(hr_permissions)} 个用户相关权限")
    
    print("✅ 部门权限初始化完成")


async def init_roles():
    """初始化角色"""
    print("=== 开始初始化角色 ===")
    all_permissions = await Permission.all()
    perm_dict = {p.code: p for p in all_permissions}
    
    # 合并默认角色和扩展角色
    all_roles = DEFAULT_ROLES + EXTENDED_ROLES
    
    for role_data in all_roles:
        # 检查角色是否已存在
        existing_role = await Role.filter(code=role_data["code"]).first()
        if existing_role:
            print(f"⏩ 角色已存在: {role_data['name']} ({role_data['code']})")
            continue
            
        # 获取部门（如果指定）
        department = None
        if role_data.get("dept_id"):
            department = await Department.filter(dept_id=role_data["dept_id"]).first()
            if not department:
                print(f"⚠️ 找不到部门 {role_data['dept_id']}，角色将不关联部门")
                
        # 创建角色
        role = await Role.create(
            name=role_data["name"],
            code=role_data["code"],
            description=role_data["description"],
            department=department
        )
        
        # 分配权限
        if "*" in role_data["permissions"]:
            # 超级管理员拥有所有权限
            for perm in all_permissions:
                await role.permissions.add(perm)
            print(f"✅ 创建角色: {role_data['name']} (所有权限)" + (f", 部门: {department.dept_name}" if department else ""))
        else:
            # 其他角色按指定权限分配
            for perm_code in role_data["permissions"]:
                if perm_code in perm_dict:
                    await role.permissions.add(perm_dict[perm_code])
            print(f"✅ 创建角色: {role_data['name']} ({len(role_data['permissions'])} 个权限)" + (f", 部门: {department.dept_name}" if department else ""))
    
    print("✅ 角色初始化完成")


async def init_admin_user():
    """初始化管理员账号"""
    print("=== 初始化管理员账号 ===")
    admin_username = "admin"
    admin_password = "admin123"
    
    # 检查管理员是否已存在
    admin_user = await User.filter(username=admin_username).first()
    if not admin_user:
        # 获取总公司部门
        headquarters = await Department.filter(dept_id="0001A110000000000DHB").first()

        # 创建管理员账号
        admin_user = await UserService.create_user(
            username=admin_username,
            password=admin_password,
            email="admin@example.com",
            name="系统管理员",
            is_superuser=True,
            is_active=True,
            department_id=headquarters.dept_id if headquarters else None
        )
        
        # 分配管理员角色
        admin_role = await Role.filter(code="admin").first()
        if admin_role:
            await admin_user.roles.add(admin_role)
        
        print(f"✅ 创建管理员账号: {admin_username} (密码: {admin_password})")
    else:
        print(f"⏩ 管理员账号已存在: {admin_username}")


async def init_demo_users():
    """初始化演示用户账号"""
    print("=== 初始化演示用户 ===")
    
    # 预定义一些演示用户
    demo_users = [
        {
            "username": "tech_manager",
            "password": "password123",
            "name": "技术部经理",
            "email": "tech@example.com",
            "role_code": "user_admin",
            "dept_id": "tech",
            "gender": "男",
            "birthday": datetime(1985, 5, 15).date(),
            "address": "北京市海淀区",
            "phone": "13800138001",
            "bio": "技术部负责人，负责公司技术团队管理"
        },
        {
            "username": "finance_user",
            "password": "password123",
            "name": "财务人员",
            "email": "finance@example.com",
            "role_code": "rpa_operator",
            "dept_id": "finance",
            "gender": "女",
            "birthday": datetime(1990, 7, 22).date(),
            "address": "北京市朝阳区",
            "phone": "13900139002",
            "bio": "负责公司财务报表制作"
        },
        {
            "username": "hr_manager",
            "password": "password123",
            "name": "人事经理",
            "email": "hr@example.com",
            "role_code": "auditor",
            "dept_id": "hr",
            "gender": "女",
            "birthday": datetime(1988, 3, 8).date(),
            "address": "北京市丰台区",
            "phone": "13700137003",
            "bio": "人力资源部经理，负责招聘与培训"
        },
        {
            "username": "dev_user",
            "password": "password123",
            "name": "开发人员",
            "email": "dev@example.com",
            "role_code": "user",
            "dept_id": "rd",
            "gender": "男",
            "birthday": datetime(1995, 10, 11).date(),
            "address": "北京市昌平区",
            "phone": "13600136004",
            "bio": "后端开发工程师，Python技术栈"
        },
        {
            "username": "tester",
            "password": "password123",
            "name": "测试人员",
            "email": "test@example.com",
            "role_code": "user",
            "dept_id": "qa",
            "gender": "男",
            "birthday": datetime(1992, 12, 24).date(),
            "address": "北京市西城区",
            "phone": "13500135005",
            "bio": "测试工程师，负责产品质量保障"
        }
    ]
    
    for user_data in demo_users:
        # 检查用户是否已存在
        existing_user = await User.filter(username=user_data["username"]).first()
        if existing_user:
            print(f"⏩ 用户已存在: {user_data['username']}")
            continue
            
        # 获取部门
        department = await Department.filter(dept_id=user_data["dept_id"]).first()
        if not department:
            print(f"⚠️ 找不到部门 {user_data['dept_id']}，跳过创建用户 {user_data['username']}")
            continue
            
        # 获取角色
        role = await Role.filter(code=user_data["role_code"]).first()
        if not role:
            print(f"⚠️ 找不到角色 {user_data['role_code']}，跳过创建用户 {user_data['username']}")
            continue
            
        # 创建用户
        user = await UserService.create_user(
            username=user_data["username"],
            password=user_data["password"],
            email=user_data["email"],
            name=user_data["name"],
            gender=user_data.get("gender"),
            birthday=user_data.get("birthday"),
            address=user_data.get("address"),
            phone=user_data.get("phone"),
            bio=user_data.get("bio"),
            avatar=random.choice(AVATARS),  # 随机选择一个头像
            is_superuser=False,
            is_active=True,
            department_id=department.dept_id
        )
        
        # 分配角色
        await user.roles.add(role)
        
        print(f"✅ 创建演示用户: {user_data['username']} ({user_data['name']}, {department.dept_name})")
    
    print("✅ 演示用户初始化完成")


async def create_bulk_test_users(count=50):
    """批量创建测试用户"""
    print(f"=== 开始批量创建 {count} 个测试用户 ===")
    
    # 获取所有部门和角色
    departments = await Department.all()
    roles = await Role.all()
    
    if not departments or not roles:
        print("⚠️ 无法创建测试用户: 请先确保部门和角色已初始化")
        return
    
    # 中文姓氏
    surnames = ["张", "王", "李", "赵", "周", "吴", "郑", "陈", "冯", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "许", "何", "吕"]
    # 中文名字
    names = ["伟", "芳", "娜", "秀英", "敏", "静", "强", "磊", "洋", "艳", "勇", "军", "杰", "娟", "涛", "明", "超", "秀兰", "霞", "平"]
    
    # 地址前缀
    address_prefixes = [
        "北京市朝阳区", "上海市浦东新区", "广州市天河区", "深圳市南山区", 
        "杭州市西湖区", "成都市武侯区", "重庆市渝中区", "南京市鼓楼区",
        "武汉市洪山区", "西安市雁塔区", "天津市和平区", "苏州市姑苏区"
    ]
    
    # 职位
    positions = [
        "开发工程师", "测试工程师", "产品经理", "设计师", "运维工程师", 
        "数据分析师", "项目经理", "HR专员", "财务专员", "市场专员"
    ]
    
    # 批量创建用户
    created_count = 0
    for i in range(count):
        # 生成基本信息
        surname = random.choice(surnames)
        name = random.choice(names)
        full_name = surname + name
        
        # 用户名: 拼音缩写 + 数字
        pinyin_map = {
            "张": "zhang", "王": "wang", "李": "li", "赵": "zhao", "周": "zhou",
            "吴": "wu", "郑": "zheng", "陈": "chen", "冯": "feng", "褚": "chu",
            "卫": "wei", "蒋": "jiang", "沈": "shen", "韩": "han", "杨": "yang",
            "朱": "zhu", "秦": "qin", "许": "xu", "何": "he", "吕": "lv"
        }
        
        username = f"{pinyin_map.get(surname, 'user')}{random.randint(1000, 9999)}"
        
        # 检查用户名是否已存在
        if await User.filter(username=username).exists():
            # 如果用户名已存在，重新生成
            username = f"{pinyin_map.get(surname, 'user')}{random.randint(10000, 99999)}"
        
        # 随机选择部门和角色
        department = random.choice(departments)
        role = random.choice(roles)
        
        # 随机生成生日(25-55岁之间)
        birth_year = datetime.now().year - random.randint(25, 55)
        birth_month = random.randint(1, 12)
        birth_day = random.randint(1, 28)  # 简化处理，避免月份天数问题
        birthday = datetime(birth_year, birth_month, birth_day).date()
        
        # 随机生成地址
        address = f"{random.choice(address_prefixes)}{''.join(random.sample('0123456789', 3))}号"
        
        # 随机生成手机号
        phone = f"1{random.randint(3, 9)}{random.randint(100000000, 999999999)}"
        
        # 随机选择性别
        gender = random.choice(["男", "女"])
        
        # 随机选择职位和生成个人简介
        position = random.choice(positions)
        bio = f"{department.dept_name}{position}，{''.join(random.sample('专注敬业有责任感团队合作创新思维技术精湛经验丰富积极向上乐于助人', random.randint(10, 20)))}"
        
        # 随机选择头像或为空
        avatar = random.choice([None] + AVATARS)
        
        try:
            # 创建用户
            user = await UserService.create_user(
                username=username,
                password="password123",  # 统一密码便于测试
                email=f"{username}@example.com",
                name=full_name,
                gender=gender,
                birthday=birthday,
                address=address,
                phone=phone,
                bio=bio,
                avatar=avatar,
                is_superuser=False,
                is_active=True,
                department_id=department.dept_id
            )
            
            # 分配角色
            await user.roles.add(role)
            
            created_count += 1
            if created_count % 10 == 0:
                print(f"✅ 已创建 {created_count}/{count} 个测试用户")
            
        except Exception as e:
            print(f"❌ 创建用户 {username} 失败: {str(e)}")
    
    print(f"✅ 批量创建测试用户完成，成功创建 {created_count} 个用户")


async def init_rbac():
    """初始化RBAC权限管理系统"""
    await init_tortoise()
    
    try:
        # 初始化权限
        await init_permissions()
        
        # 初始化部门
        await init_departments()
        
        # 初始化角色
        await init_roles()
        
        # 初始化管理员账号
        await init_admin_user()
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"❌ 初始化RBAC系统失败: {e}")
    finally:
        await close_tortoise()


async def main():
    """初始化数据"""
    try:
        # 初始化 Tortoise ORM
        await init_tortoise()
        
        # 初始化权限
        await init_permissions()
        
        # 初始化部门
        await init_departments()
        
        # 初始化角色
        await init_roles()
        
        # 初始化用户
        await init_demo_users()
        
        # 使用refresh_token和其他权限测试
        # await test_login()
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"❌ 初始化数据失败: {e}")
    finally:
        await Tortoise.close_connections()


async def init_admin_only():
    """仅初始化管理员账号"""
    await init_tortoise()
    
    try:
        # 初始化权限
        await init_permissions()
        
        # 初始化部门
        await init_departments()
        
        # 初始化角色
        await init_roles()
        
        # 初始化管理员账号
        await init_admin_user()
        
        print("✅ 管理员账号初始化完成")
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"❌ 初始化管理员账号失败: {e}")
    finally:
        await Tortoise.close_connections()


if __name__ == "__main__":
    try:
        # 解析命令行参数
        parser = argparse.ArgumentParser(description="初始化数据库数据")
        parser.add_argument("--admin-only", action="store_true", help="只初始化管理员账号")
        parser.add_argument("--bulk-users", type=int, help="批量创建指定数量的测试用户")
        parser.add_argument("--all", action="store_true", help="初始化所有数据")
        args = parser.parse_args()
        
        if args.admin_only:
            # 只初始化管理员
            asyncio.run(init_admin_only())
        elif args.bulk_users:
            # 初始化 Tortoise ORM
            asyncio.run(Tortoise.init(config=TORTOISE_ORM))
            try:
                # 批量创建测试用户
                asyncio.run(create_bulk_test_users(args.bulk_users))
            finally:
                asyncio.run(Tortoise.close_connections())
        elif args.all:
            # 初始化所有数据
            asyncio.run(main())
        else:
            # 如果没有提供任何参数，显示帮助信息
            print("请指定要执行的操作，可选参数如下：")
            print("  --admin-only    只初始化管理员账号")
            print("  --bulk-users N  批量创建N个测试用户")
            print("  --all           初始化所有数据")
            print("\n示例：")
            print("  python -m backend.tests.make_data --admin-only")
            parser.print_help()
    except KeyboardInterrupt:
        print("\n👋 已退出。")
